// 在线申请
import React, { useEffect, useState } from 'react';
import {
  Table,
  Input,
  Select,
  Space,
  Form,
  ConfigProvider,
  Button,
  Row,
  Col,
  message,
  Spin,
} from 'antd';
import { getOnlineApplication } from '@/services/homePage/homePage';
import zhCN from 'antd/lib/locale/zh_CN';
import { SearchOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import type { Dispatch } from 'umi';
import type { ConnectState, homePageState } from '@/models/connect';
import { history } from '@@/core/history';
import classnames from 'classnames';
import { getIsLogin, highLight, newsDetail } from '@/utils/util';
import styles from './index.less';

const { Option } = Select;

const layout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 17 },
};
interface propsType {
  dispatch: Dispatch;
  homePageRedux: homePageState;
}

const OnlineApplicationTable: React.FC<propsType> = (props) => {
  const { dispatch, homePageRedux } = props;
  const { businessDept } = homePageRedux;
  useEffect(() => {
    dispatch({
      type: 'homePage/initHomePageData',
      payload: {},
    });
  }, []);

  const [onlineApplicationData, setOnlineApplicationData] = useState([]);
  const [searchCondition, setSearchCondition] = useState({});

  const initPagination = { page: 1, size: 10 };
  const [totalCount, setTotalCount] = useState(0);
  const [loading, setLoading] = useState(false);

  const getApplicationList = (params, condition) => {
    setLoading(true);
    getOnlineApplication({ ...params, ...condition })
      .then((resp) => {
        const data = resp.results?.map((item: { id: any }) => {
          return {
            // table需要key
            key: item?.id,
            ...item,
          };
        });
        setTotalCount(resp?.totalCount);
        setOnlineApplicationData(data);
        setLoading(false);
      })
      .catch((error) => {
        throw error;
        setLoading(false);
      });
  };

  useEffect(() => {
    getApplicationList(initPagination, searchCondition);
  }, [searchCondition]);

  const gotoPolicy = (item) => {
    try {
      history.push({ pathname: '/PolicyDeclare', query: { id: item.id } });
      highLight(dispatch, 'policyList');
    } catch (error) {
      message.error('请联系管理员');
    }
  };

  const gotoOnlineApply = (record: any) => {
    if (!getIsLogin()) {
      message.error('请先登录');
      history.push({ pathname: '/' });
      return;
    }
    if (record.matterStatus === '01') {
      message.error('未开始申报');
      return;
    }
    if (record.matterStatus === '03') {
      message.error('已截止申报');
      return;
    }
    if (record.matterStatus === '02') {
      history.push({ pathname: '/onlineApply', query: { id: record.id } });
      highLight(dispatch, 'policyList');
    }
  };

  const columns = [
    {
      title: '业务主管部门',
      dataIndex: 'orgName',
      key: 'orgName',
      width: 80,
    },
    {
      title: '事项名称',
      dataIndex: 'title',
      key: 'title',
      width: 250,
      render: (text: string, record: any) => {
        return (
          <div
            title={text}
            style={{
              maxWidth: 200,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
            }}
          >
            {text}
          </div>
        );
      },
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      width: 100,
      render: (record) => {
        return (
          <Space>
            <div
              className={classnames(`${styles.tableOpt}`)}
              onClick={gotoOnlineApply.bind('', record)}
            >
              在线申请
            </div>
            <div className={classnames(`${styles.tableOpt}`)} onClick={gotoPolicy.bind('', record)}>
              查看政策
            </div>
          </Space>
        );
      },
    },
  ];

  const onFinish = (values: any) => {
    const { orgId, title } = values;
    setSearchCondition({
      orgId,
      title,
      // page: 1,
      // size: 10,
    });
  };

  function handleChange(value: any) {
    console.log(`业务部门下拉选选中 ${value}`);
  }

  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.OnlineApplicationWrapper}>
        <div className={styles.OnlineApplicationTitle}>
          <div className={styles.titleLeft}>
            <div className={styles.sideShortBar}></div>
            <div className={styles.titleText}>在线申请</div>
          </div>
          <div className={styles.titleRight}>
            <Form {...layout} className={styles.OnlineApplicationForm} onFinish={onFinish}>
              <Row>
                <Col>
                  <Form.Item label="业务部门" name="orgId">
                    <Select
                      placeholder="全部"
                      style={{ width: 200 }}
                      onChange={handleChange}
                      allowClear
                      className={styles.SelectDept}
                    >
                      {businessDept?.length &&
                        businessDept?.map((obj) => {
                          return (
                            <Option key={obj.id} value={obj.id}>
                              {obj.orgName}
                            </Option>
                          );
                        })}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={1}></Col>
                <Col>
                  <Form.Item label="事项名称" name="title">
                    <Input className={styles.SearchInput} placeholder="请输入要搜索的事项名称" />
                  </Form.Item>
                </Col>
                <Col>
                  <Form.Item>
                    <Button
                      className={styles.SearchInput}
                      type="primary"
                      htmlType="submit"
                      icon={<SearchOutlined />}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={styles.OnlineApplicationTable}>
          <ConfigProvider locale={zhCN}>
            <Spin spinning={loading}>
              <Table
                columns={columns}
                dataSource={onlineApplicationData}
                size="middle"
                pagination={{
                  locale: zhCN,
                  total: totalCount,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total) => {
                    return `共${total}条数据`;
                  },
                  onChange: (page, pageSize) => {
                    getApplicationList({ page, size: pageSize }, searchCondition);
                  },
                }}
              />
            </Spin>
          </ConfigProvider>
        </div>
      </div>
    </ConfigProvider>
  );
};

export default connect(({ homePage }: ConnectState) => ({
  homePageRedux: homePage,
}))(OnlineApplicationTable);
